package com.jeeos.framework.utils;
import cn.hutool.json.JSONObject;
import com.nimbusds.jose.JWSObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

public class UserUtils {

    public static String getUserName() {
        //从Header中获取用户信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("Authentication");
        if(StringUtils.isNotEmpty(token)){
            try {
                //从token中解析用户信息并设置到Header中去
                String realToken = token.replace("Bearer ", "");

                JWSObject jwsObject = JWSObject.parse(realToken);
                String userStr = jwsObject.getPayload().toString();
                JSONObject userJsonObject = new JSONObject(userStr);
                return userJsonObject.getStr("user_name");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static void main(String[] args) {

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode("123456");
        System.out.println(encode);
    }
}
